import fetch from 'dva/fetch';
import createHistory from 'history/createHashHistory';
import queryString from 'query-string';

const history = createHistory();

/**
 * Requests a URL, returning a promise.
 *
 * @param  {string} url       The URL we want to request
 * @param  {object} [options] The options we want to pass to "fetch"
 * @return {object}           An object containing either "data" or "err"
 */
export async function request(url, options) {
  const response = await fetch(url, {
    ...options,
    credentials: 'include',
    headers: {
      Accept: 'application/json, text/javascript, */*; q=0.01',
      'Content-Type': 'application/json; charset=UTF-8',
    },
  });
  let data = {
    code: -1,
  };

  if (response.status >= 200 && response.status < 300) {
    data = await response.json();
  } else {
    data = {
      code: -1,
      msg: `发生未知错误(code:${response.status})`,
    };
  }
  if (data.rspCd == '30002' || data.rspCd == 'M0001') {
    history.push('/login');
  }

  return { data };
}

/**
 * json对象转换成query string
 *
 * @param {object} json An json object
 * @return {string}
 */
export function jsonToQueryString(json) {
  if (json) {
    return Object.keys(json).map((key) => {
      if (json[key] instanceof Array) {
        return Object.keys(json[key]).map((k) => {
          let value = json[key][k];
          if (typeof value != 'object' && value != undefined && value != null) {
            value = value.toString();
          } else {
            value = '';
          }
          return `${encodeURIComponent(key)}=${encodeURIComponent(value)}`;
        }).join('&');
      }
      let value = json[key];
      if (typeof value != 'object' && value != undefined && value != null) {
        value = value.toString();
      } else {
        value = '';
      }
      return `${encodeURIComponent(key)}=${encodeURIComponent(value)}`;
    }).join('&');
  }
  return '';
}
/**
 * query string转换成json对象
 * @param {*} queryString
 */
export function queryStringToJson(queryString) {
  const json = {};
  if (queryString) {
    if (queryString.indexOf('?') == 0) {
      queryString = queryString.slice(1);
    }
    const fields = queryString.split('&');
    fields.forEach((field) => {
      const pairs = field.split('=');
      if (pairs && pairs.length > 1 && pairs[0] && pairs[1]) {
        const tmp = json[pairs[0]];
        if (tmp) {
          if (tmp instanceof Array) {
            json[pairs[0]].push(pairs[1]);
          } else {
            json[pairs[0]] = [tmp, pairs[1]];
          }
        } else {
          json[pairs[0]] = pairs[1];
        }
      }
    });
  }
  return json;
}
/**
 * 修改键值对数组的键值名
 * 因为antd中的select、checkbox等组件的数据源仅支持label、value、children为键值名
 *
 * @param {*} param
 */
export function generateLabelValueList(param) {
  const { list, labelIndex, valueIndex, keyIndex, isLeafIndex, childIndex } = param;
  const resultList = [];
  if (list && list.length > 0) {
    list.forEach((item, key) => {
      resultList.push({
        ...item,
        label: labelIndex && item[labelIndex],
        value: valueIndex && item[valueIndex],
        key: keyIndex && item[keyIndex],
        isLeaf: !!(isLeafIndex && item[isLeafIndex]),
      });
      if (childIndex && item[childIndex] && item[childIndex].length > 0) {
        const child = generateLabelValueList({
          list: item[childIndex],
          labelIndex,
          valueIndex,
          keyIndex,
          isLeafIndex,
          childIndex,
        });
        if (child && child.length > 0) {
          resultList[key].children = child;
        }
      }
    });
  }
  return resultList;
}
/**
 * 给数值添加逗号（千分位表示法）
 * @param {*} value
 */
export function comma(value = '') {
  value = (value / 100).toFixed(2);
  const tmp = value.split('.');
  tmp[0] = tmp[0].replace(/\d{1,3}(?=(\d{3})+$)/g, i => `${i},`);
  return tmp.join('.');
}
/**
 * 异步加载json数据（静态JSON文件，跨域请求，只可以用于请求静态资源）
 * @param {*} url
 */
export async function loadStaticJSONData(url) {
  const response = await fetch(url, {
    mode: 'cors',
    headers: {
      Accept: 'application/json, text/javascript, */*; q=0.01',
      'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',
    },
  });
  let data = {};
  if (response.status >= 200 && response.status < 300) {
    data = await response.json();
  }
  return data;
}

// 解析url参数
export function urlParsed(location) {
  return queryString.parse(location);
}
// 码云
// lvlip
// chenyang1993